package com.concurrency;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @program: concurrency
 * @description: 并发测试
 * @author: yulongguang
 * @create: 2018-06-27 22:17
 **/
@Slf4j
public class ConcurrencyTest {

    //请求总数
    private static int clientTotal = 5000;

    //同时并发执行的线程数
    private static int threadTotal = 500;

    //计数
    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        //线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        //信号量
        final Semaphore semaphore = new Semaphore(threadTotal);
        //计数递减
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {

            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    log.error("exception" + e.getMessage());
                }
                //递减
                countDownLatch.countDown();

            });
        }
        log.info("count:{}", count);
        countDownLatch.await();
        executorService.shutdown();
        log.info("count:{}" + count);

    }

    private static void add() {
        count++;
    }
}
